package net.bingosoft.common.struts.plugin;

import javax.servlet.ServletException;

import net.bingosoft.common.EncodedProperties;
import net.bingosoft.common.ObjectRegistry;
import net.bingosoft.common.config.Config;
import net.bingosoft.common.struts.CustomizedRequestProcessor;

import org.apache.log4j.Logger;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.action.RequestProcessor;
import org.apache.struts.config.ModuleConfig;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 2007-10-18 下午05:06:05
 * Author:yangdongyu(yangdy@bingosoft.net)
 * ReadMe:系统初始化的PlugIn,目前主要用户ObjectRegistry的初始化,解决和dwr集成的问题
 * ChangeLog:
 */
public class SystemInitPlugIn implements PlugIn {
	/**
	 * Logger for this class
	 */
	protected static final Logger logger = Logger.getLogger(SystemInitPlugIn.class);


	/* (non-Javadoc)
	 * @see org.apache.struts.action.PlugIn#destroy()
	 */
	public void destroy() {

	}

	/* (non-Javadoc)
	 * @see org.apache.struts.action.PlugIn#init(org.apache.struts.action.ActionServlet, org.apache.struts.config.ModuleConfig)
	 */
	public void init(ActionServlet servlet, ModuleConfig config)
	throws ServletException {
		//Find the root WebApplicationContext for this web application, which is
		//typically loaded via ContextLoaderListener or ContextLoaderServlet.
		ObjectRegistry.setOverrideFactory(WebApplicationContextUtils.getWebApplicationContext(servlet.getServletContext()));
		//初始化BeanFactory
		BeanFactory factory = ObjectRegistry.getApplicationContext();
		CustomizedRequestProcessor.setOverrideBeanFactory(factory);
		EncodedProperties.GLOBEL_ENABLE_RELOAD = Config.getBoolean("UNDER_DEVELOP", true);

		//处理重新加载struts配置文件
		String processorKey = Globals.REQUEST_PROCESSOR_KEY + config.getPrefix();
		RequestProcessor processor = (RequestProcessor)servlet.getServletContext().getAttribute(processorKey);
		if(processor != null){
			processor.init(servlet, config);
		}

//		try{
//			logger.debug("尝试初始化org.directwebremoting.spring.SpringCreator ...");
//			Class springCreator = Class.forName("org.directwebremoting.spring.SpringCreator");
//			springCreator.getMethod("setOverrideBeanFactory", new Class[]{BeanFactory.class}).invoke(springCreator, factory);
//			logger.debug("初始化org.directwebremoting.spring.SpringCreator完成");
//		}catch(Exception ex){
//			logger.warn("初始化org.directwebremoting.spring.SpringCreator出错,如果您没有使用dwr,您可以忽略该错误...");
//		}

	}

}
